package com.weixing.mall.provider.listener;

import com.alibaba.fastjson.JSONObject;
import com.weixing.mall.provider.model.domain.JobLogs;
import org.quartz.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

/**
 * @author jzy
 * @date 2020/5/9
 */
public class JobLogsListener implements JobListener {
    @Override
    public String getName() {
        return "JobLogsListener";
    }
    /**
     * 调度前执行
     *
     * @param job
     */
    @Override
    public void jobToBeExecuted(JobExecutionContext job) {

    }

    @Override
    public void jobExecutionVetoed(JobExecutionContext job) {

    }
    /**
     * 调度完成或异常时执行
     *
     * @param job
     * @param e
     */
    @Override
    public void jobWasExecuted(JobExecutionContext job, JobExecutionException e) {
        JobDetail detail = job.getJobDetail();
        JobDataMap dataMap = detail.getJobDataMap();
        String jobName = detail.getKey().getName();
        String jobGroup = detail.getKey().getGroup();
        String jobClass = detail.getJobClass().getName();
        String description = detail.getDescription();
        String exception = null;
        String cronExpression = null;
        Integer status = 1;
        Trigger trigger = job.getTrigger();
        String triggerClass = trigger.getClass().getName();
        Long repeatInterval = 0L;
        Integer repeatCount = 0;
        Date startDate = null;
        Date endDate = null;
        if (trigger instanceof CronTrigger) {
            CronTrigger cronTrigger = (CronTrigger) trigger;
            cronExpression = cronTrigger.getCronExpression();
        }else if (trigger instanceof SimpleTrigger) {
            SimpleTrigger simpleTrigger = (SimpleTrigger) trigger;
            repeatInterval = simpleTrigger.getRepeatInterval();
            repeatCount = simpleTrigger.getRepeatCount();
            startDate = simpleTrigger.getStartTime();
            endDate = simpleTrigger.getEndTime();
        }
        if (e != null) {
            status = 0;
            StringWriter stringWriter = new StringWriter();
            e.printStackTrace(new PrintWriter(stringWriter));
            exception=stringWriter.toString();
        }
        JobLogs jobLog = new JobLogs();
        jobLog.setJobName(jobName).setJobGroup(jobGroup).setJobClass(jobClass).setJobDescription(description).setRunTime(job.getJobRunTime()).setCreateTime(new Date());
        jobLog.setCronExpression(cronExpression).setTriggerClass(triggerClass).setRunStartTime(job.getFireTime()).setException(exception).setJobData(JSONObject.toJSONString(dataMap));
        jobLog.setRunEndTime(new Date(job.getFireTime().getTime() + job.getJobRunTime())).setStatus(status).setRepeatInterval(repeatInterval).setRepeatCount(repeatCount);
        jobLog.setStartTime(startDate).setEndTime(endDate);
        jobLog.insert();
    }
}
